<?php
	session_start();
	/**
	* @package admin
	* @desc This php file is used to delete users from the database.
	*/
	

	if ($_SESSION["role"] != "admin")
	{
		header('Location: ../index.php');
		exit();
	}
	
	// Direct calling check
	if(!isset($_POST['delete']))	
		die("Do not call directly)");
	
	
	if($_POST['delete'] == "Cancel")
	{
		$name = $_SESSION['userresults']['name'];
		$email = $_SESSION['userresults']['email'];
		$role = $_SESSION['userresults']['role'];
		
		header("Location: ./userresults.php?name=$name&email=$email&role=$role&submit=Find");
		exit();
	}


	// Get variable
	$user_id = $_POST["user_id"];

	/**
	* @desc This include file connects to the database.
	*/
	require '../includes/connect.inc';

	//check if user exists
	$user = "SELECT user_id FROM users WHERE user_id = $user_id";

	//run query
	$result = mysql_query($user, $connection);
	
	$name = $_SESSION['userresults']['name'];
	$email = $_SESSION['userresults']['email'];
	$role = $_SESSION['userresults']['role'];
	
	if (!$result)
	{
		header("Location: ./userresults.php?name=$name&email=$email&role=$role&submit=Find");
		exit();
	}
		
	if(mysql_num_rows($result) < 1)
	{
		header("Location: ./userresults.php?name=$name&email=$email&role=$role&submit=Find");
		exit();
	}			

	deleteuser($user_id);

	// Disconnect
	mysql_close($connection);
	
	header("Location: userdeleted.php");
	exit();

	
	
	//--------------------------------------------------
	/**
	*@desc Function to delete user from the database
	*@param int $user_id
	*/
	function deleteuser($user_id)
	{
		global $connection;
		
		//prepare queries
		$deleteuser = "DELETE FROM users WHERE user_id = $user_id";
		$deletecomments = "DELETE FROM comments WHERE user_id = $user_id";
		$deleteproposals = "DELETE FROM proposals WHERE user_id = $user_id";
		$deleteratings = "DELETE FROM ratings WHERE user_id = $user_id";
		$deletereports = "DELETE FROM reports WHERE user_id = $user_id";
		
		//run queries
		if (!$result = mysql_query ($deletecomments, $connection))
			die("Failed to delete user comments");
		if (!$result = mysql_query ($deleteproposals, $connection))
			die("Failed to delete user equipment");
		if (!$result = mysql_query ($deleteratings, $connection))
			die("Failed to delete user ratings");
		if (!$result = mysql_query ($deletereports, $connection))
			die("Failed to delete user reports");
		if (!$result = mysql_query ($deleteuser, $connection))
			die("Failed to delete USER");
	}
	
	
?>